<template>
  <div class="app-container">
    <div class="header">
      <el-form ref="queryFormRef" :inline="true" :model="queryParams">
        <el-form-item label="部门名称" prop="keywords">
          <el-input v-model="queryParams.keywords" placeholder="请输入部门名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="部门状态" style="width: 150px" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery" :loading="loading">查询</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <div class="util">
        <el-button type="primary" v-hasPermi="['sys:dept:add']" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          新增部门
        </el-button>
      </div>
      <div class="table-inner">
        <el-table v-loading="loading" :data="deptList" row-key="id" default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border>
          <el-table-column prop="name" label="部门名称" width="500px" show-overflow-tooltip />
          <el-table-column prop="address" label="地址" width="280" :show-overflow-tooltip="true" align="center" />
          <el-table-column prop="textArea" label="详细地址" align="center" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.textArea ? row.textArea : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" align="center" />

          <el-table-column prop="status" label="部门状态" align="center">
            <template #default="scope">
              <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" inline-prompt active-text="正常"
                inactive-text="停用" @change="handleStatusChange($event, scope.row)" />
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip />
          <el-table-column label="操作" align="center" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" link size="small" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['sys:dept:edit']"> 编辑 </el-button>
              <el-button type="danger" link size="small" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['sys:dept:delete']"> 删除 </el-button>
            </template>

          </el-table-column>
        </el-table>
      </div>
    </div>
    <DeptDialog ref="deptDialogRef" @success="getList" />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus'
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import DeptDialog from './components/deptDialog.vue'
import { listDept, delDept, changeDeptStatus } from '@/api/dept'

// 遮罩层
const loading = ref(false)
// 部门列表
const deptList = ref([])
// 查询表单ref
const queryFormRef = ref<FormInstance>()
// 对话框ref
const deptDialogRef = ref()

// 查询参数
const queryParams = reactive({
  keywords: '',
  status: undefined
})

/** 查询部门列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await listDept(queryParams)
    deptList.value = res.data
  } catch (error: any) {
    ElMessage.error(error.msg || '查询失败')
  } finally {
    loading.value = false
  }
}

/** 查询按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 新增按钮操作 */
const handleAdd = (row?: any) => {
  deptDialogRef.value.show(row)
}

/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  deptDialogRef.value.show(row)
}

/** 删除按钮操作 */
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `是否确认删除名称为"${row.name}"的部门?`,
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(async () => {
      try {
        const params = new URLSearchParams()
        params.append('ids', row.id)
        await delDept(params, row.id)
        getList()
        ElMessage.success("删除成功")
      } catch (error: any) {
        ElMessage.error(error.msg || '删除失败')
      }
    })
    .catch(() => { })
}

/** 部门状态修改 */
const handleStatusChange = async (value: string, row: any) => {
  const text = value == 1 ? '启用' : '停用'
  try {
    await ElMessageBox.confirm(
      `确认要${text}"${row.name}"部门吗?`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    )

    const formData = new FormData()
    formData.append('deptId', row.id)
    formData.append('status', value)

    await changeDeptStatus(formData, row.id)
    getList()
    ElMessage.success("修改成功")
  } catch (error: any) {
    row.status = value == 0 ? 1 : 0
    if (error !== 'cancel') {
      ElMessage.error(error.msg || '修改失败')
    }
  }
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
@import '@/assets/styles/variables.module.scss';

.header {
  display: flex;
  padding: 24px;
  margin-bottom: 16px;
  border-radius: $border-radius-large;
  background: white;
  box-shadow: $box-shadow-light;
  border: 1px solid $gray-200;
  transition: $transition-base;
  
  &:hover {
    box-shadow: $box-shadow-base;
  }
  
  .el-form {
    width: 100%;
    
    .el-form-item {
      margin-bottom: 0;
      
      .el-input {
         .el-input__inner {
           border-radius: $border-radius-base;
           transition: $transition-base;
           
           &:focus {
             border-color: $primary !important;
             box-shadow: 0 0 0 2px rgba($primary, 0.1) !important;
           }
         }
       }
    }
  }
}

.footer {
  flex: 1;
  display: flex;
  padding: 24px;
  flex-direction: column;
  border-radius: $border-radius-large;
  overflow: hidden;
  background: white;
  box-shadow: $box-shadow-light;
  border: 1px solid $gray-200;
  position: relative;
  box-sizing: border-box;
  transition: $transition-base;
  
  &:hover {
    box-shadow: $box-shadow-base;
  }

  .util {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;
    
    .el-button {
      border-radius: $border-radius-base;
      font-weight: 500;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba($primary, 0.3);
      }
      
      &.el-button--primary {
        background: linear-gradient(135deg, $primary, lighten($primary, 10%));
        border-color: $primary;
      }
    }
  }

  .table-inner {
    flex: 1;
    position: relative;
    
    .el-table {
      border-radius: $border-radius-base;
      overflow: hidden;
      
      .el-table__header-wrapper {
        th {
          background-color: $gray-50 !important;
          color: $gray-700;
          font-weight: 600;
          border-bottom: 1px solid $gray-200;
        }
      }
      
      .el-table__body-wrapper {
        .el-table__row {
          transition: $transition-base;
          
          &:hover {
            background-color: $gray-50;
          }
        }
        
        .el-button {
          &.el-button--text {
            padding: 4px 8px;
            border-radius: 4px;
            transition: $transition-base;
            
            &:hover {
              background: rgba($primary, 0.1);
            }
            
            &.el-button--danger:hover {
              background: rgba($error, 0.1);
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .header {
    padding: 16px;
    
    .el-form {
      .el-row {
        .el-col {
          margin-bottom: 16px;
        }
      }
    }
  }
  
  .footer {
    padding: 16px;
    
    .util {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;
    }
  }
}
</style>